﻿using Ekton_Manage_DomainCore.Aggregate;
using Ekton_Manage_DTO.CommonModels;
using Ekton_Manage_Framework.Methods;
using Ekton_Manage_IBusiness;
using Ekton_Manage_InfrastructureCore.Common;
using Ekton_Manage_InfrastructureCore.Repositories;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Hosting;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Threading.Tasks;
using static Ekton_Manage_DTO.CommonModels.DtoFileModel;
using System.Net.Http;
using System.Net.Http.Headers;
using MimeKit;
using MailKit.Net.Smtp;
using MimeKit.Text;
using NPOI.SS.Util;
using NPOI.SS.UserModel;
using NPOI.HSSF.Util;

namespace Ekton_Manage_Web.Controllers
{
    /// <summary>
    /// 通用接口
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    [Authorize("Permission")]
    public class CommonController : ControllerBase
    {
        private readonly ICommonApi _commonApi;
        private readonly UpLoadFile _upload;
        private readonly CommonHelper _commonHelper;
        private readonly IBaseRepository<verify_code, int> _baseverifyCoderepository;
        private readonly IBaseRepository<company_email, int> _basecompanyEmailrepository;

        [Obsolete]
        private readonly IHostingEnvironment _hostingEnvironment;

        [Obsolete]
        public CommonController(ICommonApi commonApi, IHostingEnvironment hostingEnvironment, UpLoadFile upLoad, CommonHelper commonHelper, IBaseRepository<verify_code, int> baseverifyCoderepository, IBaseRepository<company_email, int> basecompanyEmailrepository)
        {
            _commonApi = commonApi;
            _hostingEnvironment = hostingEnvironment;
            _upload = upLoad;
            _commonHelper = commonHelper;
            _baseverifyCoderepository = baseverifyCoderepository;
            _basecompanyEmailrepository = basecompanyEmailrepository;
        }

        /// <summary>
        /// 查询所属公司组织
        /// </summary>
        /// 
        [HttpGet]
        [AllowAnonymous]
        public async Task<Message> GetCompany()
        {
            return await _commonApi.GetCompany();
        }

        /// <summary>
        /// 查询产品品牌
        /// </summary>
        /// 
        [HttpGet]
        public async Task<Message> GetBrand()
        {
            return await _commonApi.GetBrand();
        }
        /// <summary>
        /// 查询产品材料
        /// </summary>
        /// 
        [HttpGet]
        public async Task<Message> GetMaterial()
        {
            return await _commonApi.GetMaterial();
        }
        /// <summary>
        /// 查询系列信息
        /// </summary>
        /// 
        [HttpGet]
        public async Task<Message> GetSeriesMsg(int brandId)
        {
            return await _commonApi.GetSeriesMsg(brandId);
        }
        /// <summary>
        /// 查询全部平台
        /// </summary>
        /// 
        [HttpGet]
        public async Task<Message> GetPlatform(int series_id)
        {
            return await _commonApi.GetPlatform(series_id);
        }

        /// <summary>
        /// 查询产品分类
        /// </summary>
        /// 
        [HttpGet]
        public async Task<Message> GetProductType()
        {
            return await _commonApi.GetProductType();
        }

        /// <summary>
        /// 查询全部角色
        /// </summary>
        /// 
        [HttpGet]
        public async Task<Message> GetRoleInfo()
        {
            return await _commonApi.GetRoleInfo();
        }

        /// <summary>
        /// 根据材料的id来查询对应的颜色
        /// </summary>
        /// 
        [HttpGet]
        public async Task<Message> GetColorByMaterial(int materialId)
        {
            return await _commonApi.GetColorByMaterial(materialId);
        }

        /// <summary>
        /// 上传文件通用接口
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<Message> UploadImg(List<IFormFile> files)
        {
            #region 上传文件  
            FormData fileDatas = new();
            files.ForEach(async (m) =>
            {
                fileDatas.files.Add(new FileDataBase64
                {
                    fileByBase64 = Convert.ToBase64String(await _commonHelper.StreamToBytes(m.OpenReadStream())),
                    suffix = "." + m.FileName.Split(".")[1]
                });
            });
            var urlList = await _upload.UploadFile(fileDatas);
            return new Message(urlList);
            #endregion
        }

        /// <summary>
        /// 邮箱验证通用接口
        /// </summary>
        /// <param name="reqest"></param>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public async Task<Message> SendEmail([FromBody] SendEmailReqest reqest)
        {
            //获取随机验证码
            string RandomNum = _commonHelper.RndNum(6);
            int port = 465;//25 465 587
            var companyEmail = await _basecompanyEmailrepository.QuerySingleData(m => m.platform_id == reqest.platformId);
            if (companyEmail == null) return new Message("平台id有误！", false, 202);
            string host;
            //判断邮箱的类型,例如 xxx@163.com => 163  , xxx@qq.com => qq
            var emailType = companyEmail.email.Split("@")[1].Split(".")[0];
            //发件人的邮箱
            string from = companyEmail.email;
            //收件人的邮箱
            string to = reqest.email;
            //发件人邮箱@符前面的部分
            string userName = companyEmail.email.Split("@")[0];//用户登录名
            string password = companyEmail.author_code;//授权码
            var message = new MimeMessage();
            message.From.Add(new MailboxAddress(from));
            message.To.AddRange(new MailboxAddress[] { new MailboxAddress(to) });
            message.Subject = "验证码消息";
            var entity = new TextPart(TextFormat.Html)
            {
                Text = "您的验证码为" + RandomNum + ",该验证码只在五分钟内有效"
            };
            message.Body = entity;
            //实例化smtp对象
            SmtpClient client = new SmtpClient();
            if (emailType == "163")//163邮箱
            {
                host = "smtp.163.com";
                client.Connect(host, port, port == 465);//465端口是ssl端口
            }
            else if (emailType == "qq")//qq邮箱
            {
                host = "smtp.qq.com";
                client.Connect(host, port, port == 465);//465端口是ssl端口
            }
            else if (emailType == "126")//126邮箱
            {
                host = "smtp.126.com";
                client.Connect(host, port, port == 465);//465端口是ssl端口
            }
            else if (emailType == "yeah")//yeah邮箱
            {
                host = "smtp.yeah.net";
                client.Connect(host, port, port == 465);//465端口是ssl端口
            }
            client.Authenticate(userName, password);//授权，提供用户名和授权码
            client.Send(message);//发送邮件
            client.Disconnect(true);//取消连接

            //将所有之前发送的验证码都设为无效验证码
            var selectCode = await _baseverifyCoderepository.QueryTableList(m => m.email == reqest.email);
            foreach (var item in selectCode)
            {
                item.state = 1;
            }
            var updateCode = await _baseverifyCoderepository.UpdateManyData(selectCode);
            //添加最新的验证码
            var code = await _baseverifyCoderepository.InsertSingleData(new verify_code
            {
                code = RandomNum,
                email = reqest.email,
                state = 0
            });
            return new Message("发送邮件成功");
        }
    }
}
